<?php

namespace App\Http\Controllers\Entity\Assets;

use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Assets\AssetsRequest;
use App\Models\Entity\Assets\Assets;
use App\Models\Entity\Assets\AssetStream;
use App\Models\Import\BatchImportVassetiHistory;
use App\Models\Injection\InjectAssetiHistory;
use App\Models\Common\EntityData\Channel\Sp;
use App\Repositories\Entity\Assets\AssetsRepository;
use App\Classes\Injection\AssetiInjection;
use App\Classes\Injection\importCms;
use App\Jobs\Injection\AssetiInjectionJob;
use App\Jobs\Import\ImportAssetJob;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Excel;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
//校验
use SebastianBergmann\Diff\Exception;
use Validator;
use Auth;
use DB;
use Ftp;
use Illuminate\Support\MessageBag;

class AssetsController extends Controller
{
    use ModelForm;

    /** @var  AssetsRepository */
    private $assetsRepository;

    public function __construct(AssetsRepository $assetsRepo)
    {
        $this->assetsRepository = $assetsRepo;
    }

    /**
     * Display a listing of the Assets.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header('导入数据');
            if($request->get('assetType') == 'assets'){
                $content->body($this->gridAssets());
                $content->description('总集');
            }elseif ($request->get('assetType') == 'serials'){
                $content->body($this->gridSerials());
                $content->description('分集');
            }else{
                $content->description('');
                $content->body($this->grid());
            }
        });
    }


    public function assets(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header('导入数据');
            $content->body($this->gridAssets());
            $content->description('总集');

        });
    }



    public function serials(Request $request)
    {
        return Admin::content(function (Content $content) use ($request) {

            $content->header('导入数据');
            $content->body($this->gridSerials());
            $content->description('分集');

        });
    }

    /**
     * Show the form for creating a new Assets.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.assets.assets.create_header'));
            $content->description(__('entity.assets.assets.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Assets in storage.
     *
     * @param AssetsRequest $request
     *
     * @return Response
     */
    public function store(AssetsRequest $request)
    {
        $input = $request->all();
        $assets = $this->assetsRepository->create($input);


        Flash::success(__('entity.assets.assets.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.assets.assets.index'));

    }

    /**
     * Display the specified Assets.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $assets = $this->assetsRepository->findWithoutFail($id);

        if (empty($assets)) {
            Flash::error(__('entity.assets.assets.not_found'));

            return redirect(route('entity.assets.assets.index'));
        }

        return view('entity.assets.assets.show')->with('assets', $assets);

    }

    /**
     * Show the form for editing the specified Assets.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.assets.assets.edit_header'));
            $content->description(__('entity.assets.assets.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Assets in storage.
     *
     * @param  int              $id
     * @param AssetsRequest $request
     *
     * @return Response
     */
    public function update($id, AssetsRequest $request)
    {
        $assets = $this->assetsRepository->findWithoutFail($id);

        if (empty($assets)) {
            Flash::error(__('entity.assets.assets.not_found'));

            return redirect(route('entity.assets.assets.index'));
        }
        $input = $request->all();

        //更新媒资基本数据
        $assets = $this->assetsRepository->update($input, $id);

        //更新媒资渠道方信息
        // $stream = AssetStream::where('asset_id',$id)->first();
        // if(empty($stream)){
        //     $stream = new AssetStream();
        // }
        // $stream->asset_id = $id;
        // $stream->ogroup_asset_id = $input['stream']['ogroup_asset_id'];
        // $stream->ogroup_asset_data = $input['stream']['ogroup_asset_data'];
        //$stream->cdn_id = $input['stream']['cdn_id'];
        //$stream->stream_id = $input['stream']['stream_id'];
        //$stream->save();

        Flash::success(__('entity.assets.assets.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.assets.assets.index'));
    }

    /**
     * Remove the specified Assets from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->assetsRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.assets.assets.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $assets = $this->assetsRepository->findWithoutFail($id);

        if (empty($assets)) {
            Flash::error(__('entity.assets.assets.not_found'));

            return redirect(route('entity.assets.assets.index'));
        }

        if ($flag = $this->assetsRepository->delete($id)) {
            return response()->json(['message' => __('entity.assets.assets.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Assets::class, function (Form $form) {

            //$form->display('id', 'ID');
            $form->text('spid', 'SP 编号');
            //$form->select('status','审核状态')->options([1 => '已审核', 0 => '待审核']);
            $form->select('asset_type','类型')->options(Assets::$asset_type);
            $form->text('spasset_id', 'SP 媒资 ID');
            $form->text('spassetkit_id', 'SP 媒资包 ID');
            $form->text('title', '名称/标题');
            $form->text('subtitle', '副标题');
            $form->textarea('short_desc', '简介');
            $form->textarea('long_desc', '介绍');
            $form->select('vcat_id', '分类')->options(["电影"=>"电影","电视剧"=>"电视剧","综艺"=>"综艺","音乐"=>"音乐"]);
            $form->text('pid', '父ID');
            $form->text('subvcat_id', '子分类');
            $form->text('inject_datetime', '注入完成时间');
            //$form->text('stream.ogroup_asset_id', '渠道方媒资ID');
            //$form->text('stream.stream_id', '注入流ID');
            //$form->text('stream.cdn_id', '注入目标');
            //$form->json('stream.ogroup_asset_data', '渠道方媒资数据');
            $form->text('directors', '导演');
            $form->text('actors', '演员');
            $form->text('vlang', '语言');
            $form->text('serials', '总集数');
            $form->text('file_url', '媒资文件');
            $form->text('duration','节目时长');
            $form->select('vformat','文件格式')->options(["1"=>"ts","2"=>"3GP","3"=>"flv","4"=>"MP4","5"=>"wmv","6"=>"mp3"]);
            $form->text('tags', '关键字');
            $form->select('resolutions', '清晰度')->options(["1"=>"low低清","2"=>"标清","3"=>"hd 高清","4"=>"超清","5"=>"4k"]);
            $form->text('vbitate', '码率');
            $form->select('mediatype', '编码格式')->options(["1"=>"H264","2"=>"MPEG4","3"=>"AVS","4"=>"MPEG2","5"=>"MP3","6"=>"WMV"]);
            $form->text('pic0', '海报大图');
            $form->text('pic1', '海报中图');
            $form->text('pic2', '海报小图');
            $form->text('pic3', '海报竖图');
            $form->text('pic4', '海报横图');
            $form->text('pic5', '海报方图');
            $form->text('pinyin', '首字母拼音缩写');
            $form->text('score', '评分');
            $form->text('varea', '产地');
            $form->text('vyears', '视频年代');
            $form->text('episode', '第几集');
            $form->text('upto', '更新到集数');
            $form->display('created_at', __('base.created_at'));
            $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Assets::class, function (Grid $grid) {
            $grid->model()->spid();
            // 添加按钮
            if (Admin::user()->cannot('entity.assets.assets.create')) {
                $grid->disableCreation();
            }

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.assets.assets.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.assets.assets.destroy')) {
                    $actions->disableDelete();
                }

                $actions->prepend('<a href="'.route('entity.assets.asset_streams.index',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-list" title="注入视频流结果集"></i></a>');

                // switch (config('custom.base.media_injection.place')) {
                //     case 'guizhou':
                //         $actions->append('<a href="'.route('entity.assets.assets.inject_one_or_more',['ids'=>$actions->getKey()]).'"><i class="fa fa-file-video-o" title="媒资注入"></i></a>');
                //         $actions->append('<a href="'.route('entity.assets.assets.injectHistory',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-bar-chart" title="注入记录"></i></a>');
                //         break;
                //     case 'heilongjiang':
                $actions->append('<a href="'.route('entity.assets.assets.inject_data',['ids'=>$actions->getKey()]).'"><i class="fa fa-file-video-o" title="媒资注入数据同步"></i></a>');
                //         $actions->append('<a href="'.route('entity.assets.assets.injectHistory',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-bar-chart" title="注入数据同步记录"></i></a>');
                //         break;
                // }

                $actions->append('<a href="'.route('entity.assets.assets.importCms',['ids'=>$actions->getKey()]).'"><i class="fa fa-upload" title="导入CMS"></i></a>');
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.assets.assets.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.assets.assets.batch_destroy')) {
                        $batch->disableDelete();
                    }

                    switch (config('custom.base.media_injection.place')) {
                        case 'guizhou':
                            //批量注入
                            $batch->add('批量注入', new \App\Admin\Extensions\Tools\BatchInject('vasseti'));

                            break;
                        case 'heilongjiang':
                            //批量注入校验
                            $batch->add('批量注入数据同步', new \App\Admin\Extensions\Tools\getInjectData('vasseti'));
                            break;
                    }

                    //批量导入CMS
                    $batch->add('批量导入CMS', new \App\Admin\Extensions\Tools\BatchImportCms('vasseti'));
                });
            });

            $grid->column('id', '媒资ID')->sortable();
            //$grid->column('spid', 'SP 编号')->sortable();
            //$grid->column('asset_type', '媒资类型')->editable('select', Assets::$asset_type)->sortable();
            $grid->column('vcat_id', '媒资分类')->sortable();
            $grid->column('pid', '父媒资')->sortable()->display(function ($pid) {
                return Assets::where('spasset_id',$pid)->value('title');
                //     if(!empty($this->inject_datetime))
                //     return date("Y-m-d H:i",$this->inject_datetime);
                //     else return '';
            });
            $grid->column('spasset_id', 'SP 媒资 ID')->sortable();
            //$grid->column('spassetkit_id', 'SP 媒资包 ID')->sortable();
            //$grid->column('stream.ogroup_asset_id', '渠道 媒资 ID');
            $grid->column('title', '媒资名/标题')->sortable();
            $grid->column('subtitle', '媒资副标题')->sortable();
            // $grid->column('inject_datetime', '注入完成时间')->sortable()->display(function () {
            //     if(!empty($this->inject_datetime))
            //     return date("Y-m-d H:i",$this->inject_datetime);
            //     else return '';
            // });

            // $grid->column('status', '审核状态')->display(function ($status) {
            //     $states_array = [
            //         '0'  => ['value' => 0, 'text' => '待审核', 'class' => 'label label-danger'],
            //         '1' => ['value' => 1, 'text' => '已审核', 'class' => 'label label-success'],
            //     ];
            //     return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            // });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                $filter->disableIdFilter();
                $filter->equal('pid', '主媒资ID');
                $filter->equal('spid', 'SP 编号');
                $filter->equal('asset_type', '媒资类型')->select(Assets::$asset_type);
                $filter->equal('spasset_id', 'SP 媒资 ID');
                $filter->equal('spassetkit_id', 'SP 媒资包 ID');
                $filter->like('title', '媒资名/标题');
                $filter->between('created_at', '导入时间')->datetime();
                $filter->between('inject_datetime', '注入时间')->datetime();

            });
        });
    }

    //主媒资
    public function gridAssets(){
        return Admin::grid(Assets::class, function (Grid $grid) {
            $grid->model()->where("pid",'=','0')->spid();
            // 添加按钮
            //if (Admin::user()->cannot('entity.assets.assets.create')) {
            $grid->disableCreation();
            //}

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.assets.assets.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.assets.assets.destroy')) {
                    $actions->disableDelete();
                }

                $actions->prepend('<a href="'.route('entity.assets.asset_streams.index',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-list" title="注入视频流结果集"></i></a>');
                if(empty($actions->row->file_url)){
                    $actions->append('<a href="'.route('entity.assets.assets.index',['assetType'=>'serials','pid'=>$actions->row->spasset_id]).'"><i class="fa fa-list" title="子媒资"></i></a> ');
                }

                // switch (config('custom.base.media_injection.place')) {
                //     case 'guizhou':
                //         $actions->append('<a href="'.route('entity.assets.assets.inject_one_or_more',['ids'=>$actions->getKey()]).'"><i class="fa fa-file-video-o" title="媒资注入"></i></a>');
                //         $actions->append('<a href="'.route('entity.assets.assets.injectHistory',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-bar-chart" title="注入记录"></i></a>');
                //         break;
                //     case 'heilongjiang':
                $actions->append('<a href="'.route('entity.assets.assets.inject_data',['ids'=>$actions->getKey()]).'"><i class="fa fa-file-video-o" title="媒资注入数据同步"></i></a>');
                //         $actions->append('<a href="'.route('entity.assets.assets.injectHistory',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-bar-chart" title="注入数据同步记录"></i></a>');
                //         break;
                // }

                //$actions->append('<a href="'.route('entity.assets.assets.importCms',['ids'=>$actions->getKey()]).'"><i class="fa fa-upload" title="导入CMS"></i></a>');
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.assets.assets.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {

                $url =  route('entity.assets.assets.toolView',['sp_no' => '','config_file_select'=>'']);
                $tools->append('<a href=' .$url. ' class="btn btn-sm btn-warning pull-right" title="导入数据"><i class="fa fa-ban"></i>导入数据</a>');


                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.assets.assets.batch_destroy')) {
                        $batch->disableDelete();
                    }

                    switch (config('custom.base.media_injection.place')) {
                        case 'guizhou':
                            //批量注入
                            $batch->add('批量注入', new \App\Admin\Extensions\Tools\BatchInject('vasseti'));

                            break;
                        case 'heilongjiang':
                            //批量注入校验
                            $batch->add('批量注入数据同步', new \App\Admin\Extensions\Tools\getInjectData('vasseti'));
                            break;
                    }

                    //批量导入CMS
                    //$batch->add('批量导入CMS', new \App\Admin\Extensions\Tools\BatchImportCms('vasseti'));
                });
            });

            $grid->column('id', '媒资ID')->sortable();
            //$grid->column('spid', 'SP 编号')->sortable();
            //$grid->column('asset_type', '媒资类型')->editable('select', Assets::$asset_type)->sortable();
            $grid->column('vcat_id', '媒资分类')->sortable();
            // $grid->column('pid', '父媒资')->sortable()->display(function ($pid) {
            //     return Assets::where('spasset_id',$pid)->value('title');
            // });
            $grid->column('spasset_id', 'SP 媒资 ID')->sortable();
            //$grid->column('spassetkit_id', 'SP 媒资包 ID')->sortable();
            //$grid->column('stream.ogroup_asset_id', '渠道 媒资 ID');
            $grid->column('title', '媒资名/标题')->sortable();
            $grid->column('subtitle', '媒资副标题')->sortable();
            // $grid->column('inject_datetime', '注入完成时间')->sortable()->display(function () {
            //     if(!empty($this->inject_datetime))
            //     return date("Y-m-d H:i",$this->inject_datetime);
            //     else return '';
            // });

            // $grid->column('status', '审核状态')->display(function ($status) {
            //     $states_array = [
            //         '0'  => ['value' => 0, 'text' => '待审核', 'class' => 'label label-danger'],
            //         '1' => ['value' => 1, 'text' => '已审核', 'class' => 'label label-success'],
            //     ];
            //     return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            // });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                $filter->disableIdFilter();
                $filter->equal('pid', '主媒资ID');
                $filter->equal('spid', 'SP 编号');
                $filter->equal('asset_type', '媒资类型')->select(Assets::$asset_type);
                $filter->equal('spasset_id', 'SP 媒资 ID');
                $filter->equal('spassetkit_id', 'SP 媒资包 ID');
                $filter->like('title', '媒资名/标题');
                $filter->between('created_at', '导入时间')->datetime();
                $filter->between('inject_datetime', '注入时间')->datetime();

            });
        });
    }


    //分集
    public function gridSerials(){
        return Admin::grid(Assets::class, function (Grid $grid) {
            $grid->model()->spid()->where("pid",'!=','0');
            // 添加按钮
            //if (Admin::user()->cannot('entity.assets.assets.create')) {
            $grid->disableCreation();
            //}

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                if (Admin::user()->cannot('entity.assets.assets.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('entity.assets.assets.destroy')) {
                    $actions->disableDelete();
                }

                $actions->prepend('<a href="'.route('entity.assets.asset_streams.index',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-list" title="注入视频流结果集"></i></a>');

                // switch (config('custom.base.media_injection.place')) {
                //     case 'guizhou':
                //         $actions->append('<a href="'.route('entity.assets.assets.inject_one_or_more',['ids'=>$actions->getKey()]).'"><i class="fa fa-file-video-o" title="媒资注入"></i></a>');
                //         $actions->append('<a href="'.route('entity.assets.assets.injectHistory',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-bar-chart" title="注入记录"></i></a>');
                //         break;
                //     case 'heilongjiang':
                $actions->append('<a href="'.route('entity.assets.assets.inject_data',['ids'=>$actions->getKey()]).'"><i class="fa fa-file-video-o" title="媒资注入数据同步"></i></a>');
                //         $actions->append('<a href="'.route('entity.assets.assets.injectHistory',['asset_id'=>$actions->getKey()]).'"><i class="fa fa-bar-chart" title="注入数据同步记录"></i></a>');
                //         break;
                // }

                //$actions->append('<a href="'.route('entity.assets.assets.importCms',['ids'=>$actions->getKey()]).'"><i class="fa fa-upload" title="导入CMS"></i></a>');
            });

            // 导出按钮
            if (Admin::user()->cannot('entity.assets.assets.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {

                $url =  route('entity.assets.assets.toolView',['sp_no' => '','config_file_select'=>'']);
                $tools->append('<a href=' .$url. ' class="btn btn-sm btn-warning pull-right" title="导入数据"><i class="fa fa-ban"></i>导入数据</a>');


                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.assets.assets.batch_destroy')) {
                        $batch->disableDelete();
                    }

                    switch (config('custom.base.media_injection.place')) {
                        case 'guizhou':
                            //批量注入
                            $batch->add('批量注入', new \App\Admin\Extensions\Tools\BatchInject('vasseti'));

                            break;
                        case 'heilongjiang':
                            //批量注入校验
                            $batch->add('批量注入数据同步', new \App\Admin\Extensions\Tools\getInjectData('vasseti'));
                            break;
                    }

                    //批量导入CMS
                    //$batch->add('批量导入CMS', new \App\Admin\Extensions\Tools\BatchImportCms('vasseti'));
                });
            });

            $grid->column('id', '媒资ID')->sortable();
            //$grid->column('spid', 'SP 编号')->sortable();
            //$grid->column('asset_type', '媒资类型')->editable('select', Assets::$asset_type)->sortable();
            $grid->column('vcat_id', '媒资分类')->sortable();
            $grid->column('pid', '父媒资')->sortable()->display(function ($pid) {
                return Assets::where('spasset_id',$pid)->value('title');
                //     if(!empty($this->inject_datetime))
                //     return date("Y-m-d H:i",$this->inject_datetime);
                //     else return '';
            });
            $grid->column('spasset_id', 'SP 媒资 ID')->sortable();
            //$grid->column('spassetkit_id', 'SP 媒资包 ID')->sortable();
            //$grid->column('stream.ogroup_asset_id', '渠道 媒资 ID');
            $grid->column('title', '媒资名/标题')->sortable();
            $grid->column('subtitle', '媒资副标题')->sortable();
            // $grid->column('inject_datetime', '注入完成时间')->sortable()->display(function () {
            //     if(!empty($this->inject_datetime))
            //     return date("Y-m-d H:i",$this->inject_datetime);
            //     else return '';
            // });

            // $grid->column('status', '审核状态')->display(function ($status) {
            //     $states_array = [
            //         '0'  => ['value' => 0, 'text' => '待审核', 'class' => 'label label-danger'],
            //         '1' => ['value' => 1, 'text' => '已审核', 'class' => 'label label-success'],
            //     ];
            //     return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            // });

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                $filter->disableIdFilter();
                $filter->equal('pid', '主媒资ID');
                $filter->equal('spid', 'SP 编号');
                $filter->equal('asset_type', '媒资类型')->select(Assets::$asset_type);
                $filter->equal('spasset_id', 'SP 媒资 ID');
                $filter->equal('spassetkit_id', 'SP 媒资包 ID');
                $filter->like('title', '媒资名/标题');
                $filter->between('created_at', '导入时间')->datetime();
                $filter->between('inject_datetime', '注入时间')->datetime();

            });
        });
    }


    /**
     * 批量导入用户-视图
     * @param Request $request
     */
    public function toolView()
    {
        return Admin::content(function (Content $content) {
            $content->header('数据处理');
            $content->description('excel导入\数据表多值字段拆分');

            $tab = new Tab();
            $tab->add('ADI XML数据导入', $this->batchXmlImportForm());
            $tab->add('EXCEL数据导入', $this->batchImportForm());
            $tab->add('数据表多值字段拆分', $this->relationTableDataImportTool());

            $content->row($tab);
            //$content->row(view('entity.assets.importTool'));
        });
    }


    /**
     * 关联表拆分工具
     */
    protected function relationTableDataImportTool()
    {
        // 文件
        return Admin::form(Assets::class, function (Form $form) {
            //设置表单提交的action
            $form->setAction('/admin/entity/assets/assets/tool/database/doChange'); //admin/users/batchImport
            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                $box = new Box('Box标题', 'Box内容');
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                $tools->add('使用说明');
            });
            $databases = config('database.connections');
            $db_options = [];
            foreach ($databases as $key=>$d){
                if($d['driver']=='mysql'){
                    $db_options[$key] = $key;
                }
            }
            $form->select('databases_resource','源库')->options($db_options)->load('table_resource', '/admin/entity/assets/assets/tool/database/database');
            $form->select('table_resource','源表')->load('field_resource', '/admin/entity/assets/assets/tool/database/table');
            $form->select('field_resource','源字段');
            $form->divide();
            $form->select('databases_used','引用库')->options($db_options)->load('table_used', '/admin/entity/assets/assets/tool/database/database');
            $form->select('table_used','引用表')->load('field_used', '/admin/entity/assets/assets/tool/database/table');
            $form->select('field_used','引用值字段');
            $form->divide();
            $form->select('databases_target','映射库')->options($db_options)->load('table_target', '/admin/entity/assets/assets/tool/database/database');
            $form->select('table_target','映射表')->load('field_target_1', '/admin/entity/assets/assets/tool/database/table');
            $form->select('field_target_1','映射源表键');
            $form->text('field_target_2','映射引用表键');
        });
    }


    /**
     * XML导入工具
     */
    protected function batchXmlImportForm()
    {
        // 文件
        return Admin::form(Assets::class, function (Form $form) {
            //设置表单提交的action
            $form->setAction('/admin/entity/assets/assets/execXmlImport'); //admin/users/batchImport
            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                $box = new Box('Box标题', 'Box内容');
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                $tools->add('使用说明');
            });
            $sps = Sp::pluck('name', 'sp_no');
            $form->select('sp_no', '服务商(SP)')->options($sps);
            $form->select('asset_type','导入媒资类型')->options(Assets::$asset_type);
            $form->radio('import_type','导入方式')->options(['ftp' => 'FTP', 'local'=> '本地文件'])->default('ftp');
            $form->text('file_url', '服务器文件路径');
        });
    }

    /*
     * 执行xml 导入
     */
    public function execXmlImport(Request $request){

        $sp_no = $request->post('sp_no');
        $file_url = $request->post('file_url');
        $asset_type = $request->post('asset_type');
        $import_type = $request->post('import_type');

        // 存放视频及XML文件的ftp
        $media_injection_place = config('custom.base.media_injection.place');

        switch ($media_injection_place) {
            case 'guizhou':
                $ftp_config = config('custom.base.media_injection.guizhou_cp.'.$sp_no.'.file_ftp');
                break;
            case 'heilongjiang':
                $ftp_config = config('custom.base.media_injection.heilongjiang.'.$sp_no.'.file_ftp');
                break;
        }

        if(empty($ftp_config)){
            $message = "请联系运维人员配置存放媒资数据的FTP";
        }else{
            $ImportAssetJob = new ImportAssetJob($sp_no,$asset_type,$file_url,$ftp_config);
            $message = $ImportAssetJob->doJob($import_type);
        }

        $success = new MessageBag([
            'title'   => '导入结果',
            'message' => $message,
        ]);

        return back()->with(compact('success'));
    }

    public function database($qtype,Request $request){
        if($qtype=='database'){
            $db = $request->get('q');
            $db_info = config('database.connections.'.$db);
            $tables = DB::connection($db)->select('show tables');
            $tables = array_column($tables, 'Tables_in_'.$db_info['database']);
            $table_options = [];
            foreach ($tables as $table){
                $table_option = ['id'=> $db.','.$table,'text'=>$table];
                $table_options[] = $table_option;
            }
            return response()->json($table_options);
        }elseif($qtype=='table'){
            $q = explode(',',$request->get('q'));
            $db= $q[0];
            $table_name = $q[1];
            $fields = DB::connection($db)->select('SHOW FULL COLUMNS FROM '.$table_name);
            //print_r($fields);
            $field_options = [];
            foreach ($fields as $field){
                $field_option = ['id'=> $db.','.$table_name.','.$field->Field];
                $field_option['text'] = !empty($field->Comment) ? $field->Field.'('.$field->Comment.')' : $field->Field;
                $field_options[] = $field_option;
            }
            return response()->json($field_options);
        }elseif($qtype=='spImportConfig'){
            $media_injection_place = config('custom.base.media_injection.place');
            $config = config('custom.base.media_injection.'.$media_injection_place.'.'.$request->get('q').'.import_config');
            $field_options = [['id'=>'{}','text'=>'请选择']];
            if(!empty($config)){
                foreach ($config as $k=>$field){
                    $field_option = ['id'=> file_get_contents($field['config_json_path'])];
                    $field_option['text'] = $field['name'];
                    $field_options[] = $field_option;
                }
            }
            return response()->json($field_options);
        }elseif($qtype=='doChange'){
            // $resource = $request->input('databases_resource');
            // $databases_used = $request->input('databases_used');
            // $databases_target = $request->input('databases_target');
            // $table_resource = $request->input('table_resource');
            // $table_used = $request->input('table_used');
            // $table_target = $request->input('table_target');

            $resource = explode(',',$request->input('field_resource'));
            $used = explode(',',$request->input('field_used'));
            $target_1 = explode(',',$request->input('field_target_1'));
            $target_2 = $request->input('field_target_2');
            $resources = DB::connection($resource[0])->table($resource[1])->select('id', $resource[2])->get();
            $resources = json_decode(json_encode($resources),true);
            //dd($resources);
            $rs = true;
            foreach ($resources as $val){
                $val[$resource[2]] = explode(',',str_replace(array(',','/',' ','，'),',',$val[$resource[2]]));
                //添加关联数据
                foreach ($val[$resource[2]] as $filed_value){
                    if(empty($filed_value)) continue;
                    //先查询,如果没有写入数据
                    $refer_value = DB::connection($used[0])->table($used[1])
                        ->where($used[2], $filed_value)
                        ->value('id');

                    if(empty($refer_value)){
                        $insert_refer_data = array();
                        $insert_refer_data[$used[2]] = $filed_value;
                        $refer_value = DB::connection($used[0])->table($used[1])
                            ->insertGetId($insert_refer_data);
                    }
                    //先查询,如果没有写入数据
                    $refer_value2 = DB::connection($target_1[0])->table($target_1[1])
                        ->where([
                            [$target_1[2], '=', $val['id']],
                            [$target_2, '=', $refer_value],
                        ])
                        ->value('id');

                    if(empty($refer_value2)){
                        $target_table_data = [];
                        $target_table_data[$target_1[2]] = $val['id'];
                        $target_table_data[$target_2] = $refer_value;
                        $insert = DB::connection($target_1[0])->table($target_1[1])
                            ->insertGetId($target_table_data);
                    }
                }
            }

            $success = new MessageBag([
                'title'   => '导入结果',
                'message' => '执行成功',
            ]);

            return back()->with(compact('success'));
        }
    }



    /**
     * 批量导入的form
     */
    protected function batchImportForm()
    {
        // 文件
        return Admin::form(Assets::class, function (Form $form) {
            //设置表单提交的action
            $form->setAction(route('entity.assets.assets.batch_import')); //admin/users/batchImport
            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                $tools->add('<a class="btn btn-sm btn-info" href="'.route('entity.assets.assets.importHistory').'"><i class="fa fa-history"></i>导入历史</a>');
            });
            $sps = Sp::pluck('name', 'sp_no');
            $form->select('spid', '服务商(SP)')->options($sps)->load('config_file_select', '/admin/entity/assets/assets/tool/database/spImportConfig');
            $form->select('config_file_select', '选择导入配置');
            $form->file('file', '数据文件');
            $form->json('config', '配置文件');
        });
    }

    //弹出导入模态框
    public function toolModel(Request $request,Content $content){

        return Admin::content(function (Content $content) {
            $content->header('数据处理');
            $content->description('excel导入');
            $form = Admin::form(Assets::class, function (Form $form) {
                //设置表单提交的action
                $form->setAction(route('entity.assets.assets.batch_import')); //admin/users/batchImport
                // 编辑界面的按钮
                $form->tools(function (Form\Tools $tools) {
                    // 去掉返回按钮
                    $tools->disableBackButton();
                    // 去掉跳转列表按钮
                    $tools->disableListButton();
                    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                    $tools->add('<a class="btn btn-sm btn-info" href="'.route('entity.assets.assets.importHistory').'"><i class="fa fa-history"></i>导入历史</a>');
                });
                $sps = Sp::pluck('name', 'sp_no');
                $form->select('spid', '服务商(SP)')->options($sps)->load('config_file_select', '/admin/entity/assets/assets/tool/database/spImportConfig');
                $form->select('config_file_select', '选择导入配置');
                $form->file('file', '数据文件');
            });
            $content->row($form);

        });
    }

    /*
     * 导入历史
     */
    public function importHistory(){

        return Admin::content(function (Content $content) {
            $content->header('数据导入历史');
            $content->description('列表');
            $content->body($this->importHistoryGrid());
            $content->row(view('entity.tag.addContentTagModal'));
        });
    }

    /*
    * 导入历史详情
    */
    public function importHistoryShow($history_id){
        // 文件
        return Admin::form(BatchImportVassetiHistory::class, function (Form $form) {

            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                $tools->add('<a class="btn btn-sm btn-info" href="javascript:void(0)" onclick="$(\'#add-content-tag-modal\').modal(\'hide\')"><i class="fa fa-history"></i>关闭</a>');
            });

            $form->text('batch_no', '批次编号');
            $form->text('task_no', '任务编号');
            $form->text('done_count', '选择导入行数');
            $form->text('success_count', '成功导入行数');
            $form->text('created_at', '导入时间');
            $form->text('file_url', '数据文件路径');
            $form->textarea('content', '配置文件');
        })->edit($history_id);

    }

    public function importHistoryGrid(){
        return Admin::grid(BatchImportVassetiHistory::class, function (Grid $grid) {

            // 添加按钮
            //if (Admin::user()->cannot('entity.assets.assets.create')) {
            $grid->disableCreation();
            //}

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                //if (Admin::user()->cannot('entity.assets.assets.edit')) {
                $actions->disableEdit();
                //}
                // 删除按钮
                //if (Admin::user()->cannot('entity.assets.assets.destroy')) {
                $actions->disableDelete();
                //}
                $actions->append('<a href="/admin/entity/assets/assets/tool/importHistory/'.$actions->getKey().'" data-toggle="modal"  data-target="#add-content-tag-modal" title="详情"><i class="fa fa-edit"></i></a>');

            });

            // 导出按钮
            if (Admin::user()->cannot('entity.assets.assets.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    //if (Admin::user()->cannot('entity.assets.assets.batch_destroy')) {
                    $batch->disableDelete();
                    //}
                });
            });
            $grid->column('id', '媒资ID')->sortable();
            $grid->column('batch_no', '批次编号')->sortable();
            $grid->column('task_no', '任务编号')->sortable();
            $grid->column('done_count', '选择导入行数')->sortable();
            $grid->column('success_count', '成功导入行数')->sortable();
            $grid->column('created_at', '导入时间')->sortable();
            $grid->column('file_url', '数据文件路径')->sortable();
            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                $filter->disableIdFilter();
                $filter->equal('batch_no', '批次编号');
                $filter->equal('task_no', '任务编号');
                $filter->between('created_at', '导入时间')->datetime();

            });
        });
    }

    /**
     * 批量导入
     * [batchImport description]
     * @return [type] [description]
     */
    public function batchImport(Request $request)
    {
        //解析配置文件
        $input = $request->all();
        $import_config = json_decode($input['config']);

        //定义校验, 没有移到request
        $validator = Validator::make($request->all(), [
            'file' => 'required', //|mimes:xls,csv,xlsx
        ], [
            'required' => ':attribute 未上传',
            //'mimes' => '文件格式只能为 :attribute',
        ], [
            'file' => '文件',
        ]);
        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }


        //方式2上传文件:
        $file = $request->file('file');
        if(!$file->isValid()){
            Flash::error('文件上传失败');
            return back()->withInput(); //关联持久用户提交的信息
        }

        //允许上传的文件格式
        $allowed_extensions = ["xls", "xlsx", "csv"]; //xlsm
        $entension          = $file->getClientOriginalExtension(); //上传文件的后缀, 扩展名
        if ($entension && !in_array($entension, $allowed_extensions)) {
            Flash::error('文件格式只能为xls, xlsx, csv');
            return back()->withInput(); //关联持久用户提交的信息
        }
        //获取文件尺寸
        $size          = $file->getSize();
        $file_max_size = config('inventory.base.file_max_size'); //文件最大限制, 现在是10M
        $size = round($file->getSize() / 1024 / 1024);
        if ($size > $file_max_size) {
            Flash::error('文件最大只能10M');
            return back()->withInput(); //关联持久用户提交的信息
        }

        $originalName = $file->getClientOriginalName(); // 文件原名
        $type         = $file->getClientMimeType(); // image/jpeg
        $realPath     = $file->getRealPath(); //临时文件的绝对路径
        $fileName     = date('YmdHis') . '-' . uniqid();
        $newName      = $fileName . '.' . $entension; //'xls';
        // 文件上传的根路径
        $rootDir     = config('filesystems.disks.admin.root');
        $path        = $file->move($rootDir . '/import_user/'.Admin::user()->id, $newName);
        $cretae_path = $rootDir . '/import_user/'. Admin::user()->id . '/' . $newName;
        //保存日志时文件路径
        $file_url = '/import_user/'. Admin::user()->id . '/' . $newName;
        $user_id  = Admin::user()->id;


        //导入开始时间
        $starttime = microtime(true);
        //读取sheets数据

        $res = [];
        Excel::selectSheets($import_config->sheetname)->load($cretae_path, function($reader) use( &$res ) {
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
        });
        //dd($import_config);
        $rowsCount = count($res)-1;
        $maxRow = (intval($import_config->row->end) < $rowsCount) ? $import_config->row->end : $rowsCount;
        $dataArray = [];
        $chartoint = array('A'=>0,'B'=>1,'C'=>2,'D'=>3,'E'=>4,'F'=>5,'G'=>6,'H'=>7,'I'=>8,'J'=>9,'K'=>10,'L'=>11,'M'=>12,'N'=>13,'O'=>14,'P'=>15,'Q'=>16,'R'=>17,'S'=>18,'T'=>19,'U'=>20,'V'=>21,'W'=>22,'X'=>23,'Y'=>24,'Z'=>25,
                           'AA'=>26,'AB'=>27,'AC'=>28,'AD'=>29,'AE'=>30,'AF'=>31,'AG'=>32,'AH'=>33,'AI'=>34,'AJ'=>35,'AK'=>36,'AL'=>37,'AM'=>38,'AN'=>39,'AO'=>40,'AP'=>41,'AQ'=>42,'AR'=>43,'AS'=>44,'AT'=>45,'AU'=>46,'AV'=>47,'AW'=>48,'AX'=>49,'AY'=>50,'AZ'=>51,
                           'BA'=>52,'BB'=>53,'BC'=>54,'BD'=>55,'BE'=>56,'BF'=>57,'BG'=>58,'BH'=>59,'BI'=>60,'BJ'=>61,'BK'=>62,'BL'=>63,'BM'=>64,'BN'=>65,'BO'=>66,'BP'=>67,'BQ'=>68,'BR'=>69,'BS'=>70,'BT'=>71,'BU'=>72,'BV'=>73,'BW'=>74,'BX'=>75,'BY'=>76,'BZ'=>77,
                           'CA'=>78,'CB'=>79,'CC'=>80,'CD'=>81,'CE'=>82,'CF'=>83,'CG'=>84,'CH'=>85,'CI'=>86,'CJ'=>87,'CK'=>88,'CL'=>89,'CM'=>90,'CN'=>91,'CO'=>92,'CP'=>93,'CQ'=>94,'CR'=>95,'CS'=>96,'CT'=>97,'CU'=>98,'CV'=>99,'CW'=>100,'CX'=>101,'CY'=>102,'CZ'=>104,
        );


        //取出referto字段数据
        $referto_array = $referto_array_key = [];
        foreach ($import_config->referto as $val){
            $referto_array_key[] = $val->field;
            $referto_array[$val->field] = $val;
        }

        //取出transformer字段数据
        $transformer_array = $transformer_array_key = [];
        foreach ($import_config->transformer as $val){
            $transformer_array_key[] = $val->field;
            $transformer_array[$val->field] = json_decode(json_encode($val),true);
        }

        //取出rowmap字段数据
        $rowmap_array = $rowmap_array_key = [];
        foreach ($import_config->rowmap as $val){
            $rowmap_array_key[] = $val->field;
            $rowmap_array[$val->field] = json_decode(json_encode($val),true);
        }

        //处理数据
        for ($i = $import_config->row->start; $i <= $maxRow; $i++) {
            $data = array();
            foreach ($import_config->fields as $field){
                if(isset($field->value) && !empty($field->value)){
                    $data[$field->field] = $field->value;
                }elseif(isset($field->column) && is_array($field->column)){
                    foreach ($field->column as $val){
                        $data[$field->field][] = $res[$i][$chartoint[$val]];
                    }
                }elseif(isset($field->column) && !empty($field->column)){
                    $data[$field->field] = $res[$i][$chartoint[$field->column]];
                }
                //referto 字段处理
                if (is_array($referto_array_key) && in_array($field->field,$referto_array_key) && !empty($data[$field->field])){ //如果是关联字段
                    //是否多值分割符
                    if(isset($field->separtor) && !empty($field->separtor)){
                        $data[$field->field] = explode($field->separtor,$data[$field->field]);
                    }
                    //转换为数组处理
                    if(!is_array($data[$field->field])){
                        $data[$field->field] = array($data[$field->field]);
                    }

                    $referto_array_value = [];

                    foreach ($data[$field->field] as $j => $field_value){
                        if(empty($field_value)) continue;
                        //先查询,如果没有写入数据
                        $refer_value = DB::connection($import_config->database)->table($referto_array[$field->field]->table)
                            ->where($referto_array[$field->field]->map, $field_value)
                            ->value($referto_array[$field->field]->refer);

                        if(empty($refer_value)){
                            if($referto_array[$field->field]->pre == 'query'){
                                $msg  = $referto_array[$field->field]->errorMsg ? $referto_array[$field->field]->errorMsg : '请先导入'.$referto_array[$field->field]->table."数据";
                                throw new ModelNotFoundException($msg);
                            }
                            $insert_refer_data = array(
                                $referto_array[$field->field]->map=>$field_value
                            );
                            if(isset($field->default) && !empty($field->default)){
                                $defaulFieldtValues = json_decode(json_encode($field->default),true);

                                foreach ($defaulFieldtValues as $k=>$defaulFieldtValue){
                                    $insert_refer_data[$k] = is_array($defaulFieldtValue) ? $defaulFieldtValue[$j] : $defaulFieldtValue;
                                }
                            }

                            $refer_value = DB::connection($import_config->database)->table($referto_array[$field->field]->table)
                                ->insertGetId($insert_refer_data);

                        }
                        $referto_array_value[] = $refer_value;
                    }
                    $data[$field->field] = implode(",",$referto_array_value);

                }
                //transformer 字段处理
                if (!empty($transformer_array_key) && in_array($field->field,$transformer_array_key) && !empty($data[$field->field])) { //如果是transformer字段
                    if($transformer_array[$field->field]['function'] == 'trans'){
                        $data[$field->field] = str_replace(array_values($transformer_array[$field->field]['params']),array_keys($transformer_array[$field->field]['params']),$data[$field->field]);
                    }
                    elseif($transformer_array[$field->field]['function'] == 'date_time'){
                        $data[$field->field] = date($transformer_array[$field->field]['params'],strtotime($data[$field->field]));
                    }

                }

                if (empty($data[$field->field])){
                    unset($data[$field->field]);
                }
            }
            $dataArray[] = $data;
        }

        //成功的行数
        $successCount = 0;
        //总行数
        $rowsCount = count($dataArray);
        DB::beginTransaction();
        try {
            if ($import_config->row->op == 'insert') {
                foreach ($dataArray as $data) {
                    $insert_data = $data;

                    foreach ($rowmap_array_key as $rowmap_field){
                        if(isset($insert_data[$rowmap_field])){
                            unset($insert_data[$rowmap_field]);
                        }
                    }

                    $rs = DB::connection($import_config->database)->table($import_config->table)->insertGetId($insert_data);

                    //$rs = DB::table($import_config->table)->insert($data);
                    if ($rs) {
                        //成功的行数
                        $successCount++;
                        //rowmap字段数据写入
                        foreach ($rowmap_array as $k=>$rowmap){
                            if(!isset($data[$k]) || empty($data[$k])){
                                continue;
                            }
                            //多值字段关联数据写入
                            if(isset($data[$k]) && !empty($data[$k]) && !is_array($data[$k])){
                                $data[$k] = explode(",",$data[$k]);
                            }
                            $target_table_datas = array();
                            foreach ($data[$k] as $val){
                                //先查询,如果没有写入数据
                                $rowmap_value2 = DB::connection($import_config->database)->table($rowmap['table'])
                                    ->where([
                                        [$rowmap['keys'], '=', $rs],
                                        [$rowmap['rows'], '=', $val],
                                    ])
                                    ->value('id');

                                if(empty($rowmap_value2)){
                                    $target_table_data = [];
                                    $target_table_data[$rowmap['keys']] = $rs;
                                    $target_table_data[$rowmap['rows']] = $val;
                                    $target_table_datas[] = $target_table_data;
                                }
                            }
                            //dd($target_table_datas);
                            if(empty($target_table_datas)) continue;
                            DB::connection($import_config->database)->table($rowmap['table'])
                                ->insert($target_table_datas);
                        }
                    }
                }

            } elseif ($import_config->row->op == 'update') {
                foreach ($dataArray as $data) {
                    $where = array();
                    foreach ($import_config->index as $index) {
                        $where[] = [$index, '=', $data[$index]];
                    }
                    $updata = array();
                    foreach ($import_config->write as $up_field) {
                        $updata[$up_field] = $data[$up_field];
                    }

                    $rs = DB::connection($import_config->database)->table($import_config->table)
                        ->where($where)->update($updata);

                    $ids = DB::connection($import_config->database)->table($import_config->table)->where($where)->pluck('id');
                    //rowmap字段数据写入
                    foreach ($rowmap_array as $k=>$rowmap){

                        if(!isset($data[$k]) || !in_array($k,$import_config->write) || empty($data[$k])){
                            continue;
                        }

                        if(!is_array($data[$k])){
                            $data[$k] = explode(",",$data[$k]);
                        }

                        $target_table_datas = array();
                        //多值字段关联数据写入
                        foreach ($data[$k] as $val){
                            foreach ($ids as $id){
                                //先查询,如果没有写入数据
                                $rowmap_value2 = DB::connection($import_config->database)->table($rowmap['table'])
                                    ->where([
                                        [$rowmap['keys'], '=', $id],
                                        [$rowmap['rows'], '=', $val],
                                    ])
                                    ->value('id');
                                if(empty($rowmap_value2)){
                                    $target_table_data = [];
                                    $target_table_data[$rowmap['keys']] = $id;
                                    $target_table_data[$rowmap['rows']] = $val;
                                    $target_table_datas[] = $target_table_data;
                                }
                            }
                        }
                        if(empty($target_table_datas)) continue;
                        //关联表数据批量写入
                        $rs = DB::connection($import_config->database)->table($rowmap['table'])
                            ->insert($target_table_datas);
                    }

                    if ($rs) {
                        //成功的行数
                        $successCount++;
                    }
                }
            }
            DB::commit();
            $flag_rs = true;
        }catch (\Exception $e) {
            DB::rollback(); //事务回滚
            $flag_rs = false;
            $message = '<div style="word-wrap: break-word;">';
            $message .= '数据总数:';
            $message .= $rowsCount . '行<br />';
            $message .= '成功的行数:';
            $message .= $successCount . '行<br />';
            $message .= '出错了:';
            $message .= $e->getMessage() . '<br />';
            $message .= '</div>';
        }
        //导入开始时间
        $endtime = microtime(true);
        $usetime = $endtime-$starttime;

        // 创建一条记录
        $batchImportVassetiHistory                  = new BatchImportVassetiHistory;
        $batchImportVassetiHistory->batch_no        = date('YmdHis');
        $batchImportVassetiHistory->task_no         = date('YmdHis') . uniqid();
        $batchImportVassetiHistory->done_count      = $successCount;
        $batchImportVassetiHistory->file_url        = $file_url;
        $batchImportVassetiHistory->success_count   = $successCount;
        $batchImportVassetiHistory->diversity_count = 0;
        $batchImportVassetiHistory->error_count     = 0;
        $batchImportVassetiHistory->count           = $rowsCount;
        $batchImportVassetiHistory->content         = $input['config'];
        $batchImportVassetiHistory->consuming_time  = 0;
        $batchImportVassetiHistory->used_memory     = 0;
        $batchImportVassetiHistory->user_id         = Admin::user()->id;
        $batchImportVassetiHistory->save();

        if($flag_rs){
            $message = '<div style="word-wrap: break-word;">';
            $message .= '数据总数:';
            $message .= $rowsCount . '行<br />';
            $message .= '成功的行数:';
            $message .= $successCount . '行<br />';
            $message .= '运行时长:';
            $message .= $usetime . '秒<br />';
            $message .= '</div>';
        }

        $success = new MessageBag([
            'title'   => '导入结果',
            'message' => $message,
        ]);

        return back()->with(compact('success'));

    }

    /**
     * 批量媒资数据同步,获取渠道方媒资信息
     * [queryProgress description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function inject_data(Request $request)
    {
        $ids = $request->get('ids');
        $ids = explode(',',$ids);
        $count = Assets::whereIn('id', $ids)->count();

        if ($count) {
            $assetiInjection = new AssetiInjection( $ids );
            $content          = $assetiInjection->getInjectDate();
            $success = new MessageBag([
                'title'   => '数据同步提交结果',
                'message' => $content,
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title'   => '据同步提交结果',
                'message' => '参数错误',
            ]);
            return back()->with(compact('error'));
        }
    }

    /**
     * 批量导入媒资进度
     * [queryProgress description]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function bacthImportProgress(Request $request)
    {
        $taskNo = $request->input('task_no');
        $data   = BatchImportVassetiHistory::where('task_no', $taskNo)->first();
        // 记录数为0[异常]
        if ($data->count === 0) {
            return response()->json(['content' => '记录数为0!', 'status' => 'success']);
        }
        // 完成数为0
        if ($data->done_count === 0) {
            return response()->json(['content' => '0%', 'status' => 'progress']);
        }
        // 完成的时候
        if ($data->count === $data->done_count) {
            return response()->json(['content' => $data->content, 'status' => 'success']);
        }
        // 异常
        if ($data->count < $data->done_count) {
            return response()->json(['content' => '任务异常, 完成数大于总数！', 'status' => 'success']);
        }
        return response()->json(['content' => ceil($data->done_count * 100 / $data->count) . '%', 'status' => 'progress']);
    }


    /**
     * 媒资注入  待讨论
     * [injection 媒资注入]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function injection(Request $request)
    {
        // 判断有没有数据需要发布[上线的媒资]
        if ($count = Vasseti::where(['online_status' => 1, 'publish_status' => 0])->count()) {
            // 创建一条记录
            $injectVassetiHistory                 = new InjectVassetiHistory;
            $injectVassetiHistory->batch_no       = date('YmdHis');
            $injectVassetiHistory->task_no        = date('YmdHis') . uniqid();
            $injectVassetiHistory->done_count     = 0;
            $injectVassetiHistory->count          = $count;
            $injectVassetiHistory->content        = "开始";
            $injectVassetiHistory->consuming_time = 0;
            $injectVassetiHistory->used_memory    = 0;
            $injectVassetiHistory->user_id = Admin::user()->id;
            $injectVassetiHistory->save();

            // 触发队列
            dispatch(new VassetiInjectionJob($injectVassetiHistory));

            // json返回
            return response()->json(['status' => 'success', 'content' => $injectVassetiHistory->task_no]);
        } else {
            return response()->json(['status' => 'error', 'content' => '没有需要注入的剧集, 判断剧集是否上线!']);
        }
    }

    /**
     * 媒资注入进度[电视剧主集和电影]
     * [injectionProgress 媒资注入进度]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function injectionProgress(Request $request)
    {
        $taskNo = $request->input('task_no');
        $data   = InjectVassetiHistory::where('task_no', $taskNo)->first();
        if ($data) {
            // 记录数为0[异常]
            if ($data->count === 0) {
                return response()->json(['content' => '记录数为0!', 'status' => 'success']);
            }
            // 完成数为0
            if ($data->done_count === 0) {
                return response()->json(['content' => '0%', 'status' => 'progress']);
            }
            // 完成的时候
            if ($data->count === $data->done_count) {
                return response()->json(['content' => $data->content, 'status' => 'success']);
            }
            // 异常
            if ($data->count < $data->done_count) {
                return response()->json(['content' => '任务异常, 完成数大于总数！', 'status' => 'success']);
            }
            return response()->json(['content' => ceil($data->done_count * 100 / $data->count) . '%', 'status' => 'progress']);
        } else {
            return response()->json(['content' => "非法任务号, 找不到该任务号的任务!", 'status' => 'success']);
        }
    }

    /**
     * 单个或多个媒资注入功能
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function injectOneOrMore(Request $request)
    {
        $ids = $request->get('ids');
        $ids = explode(',',$ids);
        $count = Assets::whereIn('id', $ids)->count();

        if ($count) {
            // 创建一条记录

            $assetiInjection = new AssetiInjection( $ids );

            $content          = $assetiInjection->handle();

            $success = new MessageBag([
                'title'   => '注入工单提交结果',
                'message' => $content,
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title'   => '注入结果',
                'message' => '参数错误',
            ]);
            return back()->with(compact('error'));
        }


    }


    /*
     * 注入历史
     */
    public function injectHistory(){

        return Admin::content(function (Content $content) {
            $content->header('数据注入工单历史');
            $content->description('列表');
            $content->body($this->injecHistoryGrid());
            $content->row(view('entity.tag.addContentTagModal'));
        });
    }


    /*
    * 注入列表
    */
    public function injecHistoryGrid(){
        return Admin::grid(InjectAssetiHistory::class, function (Grid $grid) {
            if(!empty($_REQUEST['asset_id'])){
                $grid->model()->where('asset_id', '=', $_REQUEST['asset_id']);
            }

            // 添加按钮
            //if (Admin::user()->cannot('entity.assets.assets.create')) {
            $grid->disableCreation();
            //}

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                // 编辑按钮
                //if (Admin::user()->cannot('entity.assets.assets.edit')) {
                $actions->disableEdit();
                //}
                // 删除按钮
                //if (Admin::user()->cannot('entity.assets.assets.destroy')) {
                $actions->disableDelete();
                //}
                $actions->append('<a href="/admin/entity/assets/assets/tool/injectHistory/'.$actions->getKey().'" data-toggle="modal"  data-target="#add-content-tag-modal" title="详情"><i class="fa fa-edit"></i></a>');

            });

            // 导出按钮
            if (Admin::user()->cannot('entity.assets.assets.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    //if (Admin::user()->cannot('entity.assets.assets.batch_destroy')) {
                    $batch->disableDelete();
                    //}
                });
            });

            $grid->column('id', '媒资ID')->sortable();
            $grid->column('batch_no', '批次编号')->sortable();
            $grid->column('task_no', '任务编号')->sortable();
            $grid->column('spasset_id', 'SP媒资ID')->sortable();
            $grid->column('created_at', '工单提交时间')->sortable();
            $grid->column('done_post_status', '工单提交状态')->display(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });

            $grid->column('pic_state', '工单解析/海报注入状态')->display(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $grid->column('series_state', '主媒资数据注入状态')->display(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $grid->column('program_state', '剧集数据注入状态')->display(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1'  => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $grid->column('movie_state', '媒资文件注入状态')->display(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $grid->column('task_status', '工单状态')->display(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // // 禁用id查询框
                $filter->disableIdFilter();
                $filter->equal('batch_no', '批次编号');
                $filter->equal('task_no', '任务编号');
                $filter->equal('spasset_id', 'SP媒资ID');
                $filter->between('created_at', '注入工单提交时间')->datetime();

            });
        });
    }


    /*
    * 注入详情
    */
    public function injectHistoryShow($history_id){
        // 文件
        return Admin::form(InjectAssetiHistory::class, function (Form $form) {

            // 编辑界面的按钮
            $form->tools(function (Form\Tools $tools) {
                // 去掉返回按钮
                $tools->disableBackButton();
                // 去掉跳转列表按钮
                $tools->disableListButton();
                // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
                $tools->add('<a class="btn btn-sm btn-info" href="javascript:void(0)" onclick="$(\'#add-content-tag-modal\').modal(\'hide\')"><i class="fa fa-history"></i>关闭</a>');
            });

            $form->text('batch_no', '批次编号');
            $form->text('task_no', '任务编号');
            $form->text('spasset_id', 'SP媒资ID');
            $form->display('task_status', '工单状态')->with(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $form->display('pic_state', '工单解析与海报注入状态')->with(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $form->display('series_state', '主媒资数据注入状态')->with(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $form->display('program_state', '剧集数据注入状态')->with(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $form->display('movie_state', '媒资文件注入状态')->with(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $form->display('done_post_status', '注入工单发送状态')->with(function ($status) {
                $states_array = [
                    '0'  => ['value' => 0, 'text' => '失败', 'class' => 'label label-danger'],
                    '-1' => ['value' => -1, 'text' => '待反馈', 'class' => 'label label-info'],
                    '1' => ['value' => 1, 'text' => '成功', 'class' => 'label label-success'],
                ];
                return "<span class='".$states_array[$status]['class']."'>".$states_array[$status]['text']."</span>";
            });
            $form->textarea('done_post_result', '注入工单发送结果');
            $form->textarea('post_content', '注入工单数据');
            $form->textarea('notify_content', '收到的最新回调信息');

        })->edit($history_id);

    }

//媒资导入CMS
    public function importCms(Request $request){

        $ids = $request->get('ids');
        $ids = explode(',',$ids);
        $count = Assets::whereIn('id', $ids)->count();

        if ($count) {
            // 创建一条记录
            $importCms = new importCms( $ids );
            $content          = $importCms->handle();
            $success = new MessageBag([
                'title'   => '导入结果',
                'message' => $content,
            ]);
            return back()->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title'   => '导入结果',
                'message' => '参数错误',
            ]);
            return back()->with(compact('error'));
        }

    }

}
